package com.kjj.car.service.impl;

import com.kjj.basic.util.PageList;
import com.kjj.car.es.doc.CarDoc;
import com.kjj.car.es.repository.CarRepository;
import com.kjj.car.query.CarSearchQuery;
import com.kjj.car.service.ICarSearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CarSearchServiceImpl implements ICarSearchService {
    @Autowired
    private CarRepository repository;
    @Override
    public PageList<CarDoc> search(CarSearchQuery query) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 高级查询
        String keyword = query.getKeyword();
        if (StringUtils.isNotBlank(keyword))
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword.trim(),
                    "title","shopName","typeName","carInfo"));
        //过滤
        List<QueryBuilder> filters = boolQuery.filter();
        Integer costeffective = query.getCosteffective();
        Integer rushsale = query.getRushsale();
        Integer quasinewcar = query.getQuasinewcar();
        Integer transitivecountry = query.getTransitivecountry();
        Long carType = query.getCarType();
        if (costeffective!=null)
            filters.add(QueryBuilders.termQuery("costeffective", costeffective));
        if (rushsale!=null)
            filters.add(QueryBuilders.termQuery("rushsale", rushsale));
        if (quasinewcar!=null)
            filters.add(QueryBuilders.termQuery("quasinewcar", quasinewcar));
        if (transitivecountry!=null)
            filters.add(QueryBuilders.termQuery("transitivecountry", transitivecountry));
        if (carType!=null)
            filters.add(QueryBuilders.termQuery("typeId", carType));
        Integer carAgeType = query.getCarAgeType();
        Integer carAge = query.getCarAge();
        if (carAge!= null && carAgeType!=null) {
            Date date = new Date(new Date().getTime() - carAge * 365 * 24 * 60 * 60 * 1000);
            if (carAgeType.intValue()==0){
                filters.add(QueryBuilders.rangeQuery("registertime").gte(date));
            }else {
                filters.add(QueryBuilders.rangeQuery("reigstertime").lte(date));
            }
        }
        BigDecimal priceMax = query.getPriceMax();
        BigDecimal priceMin = query.getPriceMin();
        if (priceMin!=null)
            filters.add(QueryBuilders.rangeQuery("saleprice").gte(priceMin));
        if (priceMax!=null)
            filters.add(QueryBuilders.rangeQuery("saleprice").lte(priceMax));


        builder.withQuery(boolQuery);
        //排序
        String orderType = query.getOrderType();
        String orderField = query.getOrderField();
        //排序方式
        SortOrder sortOrder = SortOrder.DESC;
        if ("asc".equals(orderType))
            sortOrder = SortOrder.ASC;

        if ("jg".equals(orderField)){ //价格
            builder.withSort(SortBuilders.fieldSort("saleprice").order(sortOrder));
        }
        if ("cl".equals(orderField)){ //车龄
            builder.withSort(SortBuilders.fieldSort("reigstertime").order(sortOrder));
        }
        if ("lc".equals(orderField)){ //里程
            builder.withSort(SortBuilders.fieldSort("mileage").order(sortOrder));
        }
        if ("no".equals(orderField)){ //最新上架时间
            builder.withSort(SortBuilders.fieldSort("onsaletime").order(sortOrder));
        }

        //3分页
        builder.withPageable(PageRequest.of(query.getCurrentPage()-1,
                query.getPageSize()));
        //4封装数据
        Page<CarDoc> carDocs = repository.search(builder.build());
        long total = carDocs.getTotalElements();
        if (total<1) {
            return new PageList<>();
        }else {
            List<CarDoc> rows = carDocs.getContent();
            Integer pageSize = query.getPageSize();
            long totalPage = total%pageSize==0?total/pageSize:total/pageSize+1;
            //需要计算当前页
            return new PageList<>(total,rows,totalPage);
        }
    }
}
